package com.szp.spCloud.codeService.service.impl;

import com.szp.spCloud.codeService.dao.CodeRepository;
import com.szp.spCloud.codeService.feign.EmailFeignClient;
import com.szp.spCloud.codeService.service.CodeService;
import com.szp.spCloud.pojo.AuthCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class CodeServiceImpl implements CodeService {
    @Value("${myconfig.code.expireTime}")
    private int expireSeconds;
    @Autowired
    EmailFeignClient emailFeignClient;
    @Autowired
    CodeRepository codeRepository;
    @Override
    public boolean saveCode(String email) {
        String code = UUID.randomUUID().toString().replace("-", "").substring(0, 6);


        // 保存到数据库
        AuthCode authCode = new AuthCode();
        authCode.setCode(code);
        authCode.setEmail(email);

        long current = System.currentTimeMillis();
        Date currentDate = new Date(current);
        authCode.setCreateTime(currentDate);

        long expire = current + expireSeconds *60 * 1000;
        Date expireDate = new Date(expire);
        authCode.setExpireTime(expireDate);

        codeRepository.save(authCode);

        // 发送邮件
        return emailFeignClient.sendCode(email, code);
    }

    @Override
    public int validateCode(String email, String code) {
        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        Example<AuthCode> example = Example.of(authCode);
        List<AuthCode> res = codeRepository.findAll(example);
        if(null == res || res.size() == 0){
            return 1;
        }
        res.sort((item1,item2)->item1.getId() - item2.getId());
//        Collections.reverse(res);
        Date expireTime = res.get(res.size()-1).getExpireTime();
        long expireMillis = expireTime.getTime();
        if(System.currentTimeMillis() - expireMillis > 0){
            return 2;
        }else{
            return 0;
        }
    }
}
